package com.translator.engine.ai;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;

/**
 * Claude翻译引擎实现
 * 使用Anthropic Claude API进行文本翻译
 */
public class ClaudeTranslationEngine extends AbstractAITranslationEngine {
    
    private static final String API_URL = "https://api.anthropic.com/v1/messages";
    private static final String MODEL = "claude-2";
    private static final String ANTHROPIC_VERSION = "2023-06-01";
    
    /**
     * 构造函数
     */
    public ClaudeTranslationEngine() {
        super("Claude");
    }
    
    @Override
    protected String doTranslate(String sourceText, String sourceLanguageCode, String targetLanguageCode) throws Exception {
        URL url = new URL(API_URL);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setRequestProperty("x-api-key", apiKey);
        connection.setRequestProperty("anthropic-version", ANTHROPIC_VERSION);
        connection.setDoOutput(true);
        
        // 构建请求体
        String prompt = String.format("将以下%s文本翻译成%s：\n\n%s", 
                getLanguageName(sourceLanguageCode), 
                getLanguageName(targetLanguageCode), 
                sourceText);
        
        String requestBody = String.format("{\"model\":\"%s\",\"messages\":[{\"role\":\"user\",\"content\":\"%s\"}],\"max_tokens\":2000}", 
                MODEL, 
                escapeJson(prompt));
        
        // 发送请求
        try (OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream(), StandardCharsets.UTF_8)) {
            writer.write(requestBody);
        }
        
        // 读取响应
        StringBuilder response = new StringBuilder();
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8))) {
            String line;
            while ((line = reader.readLine()) != null) {
                response.append(line);
            }
        }
        
        // 解析响应
        String responseBody = response.toString();
        String translatedText = parseResponse(responseBody);
        
        return translatedText;
    }
    
    /**
     * 解析API响应，提取翻译结果
     * 
     * @param responseBody API响应体
     * @return 翻译后的文本
     */
    private String parseResponse(String responseBody) {
        // 简单解析，实际应用中应使用JSON库
        int contentStart = responseBody.indexOf("\"content\":\"") + 12;
        int contentEnd = responseBody.indexOf("\"", contentStart);
        
        if (contentStart >= 12 && contentEnd > contentStart) {
            return responseBody.substring(contentStart, contentEnd).replace("\\n", "\n");
        }
        
        return "翻译失败，无法解析响应";
    }
    
    /**
     * 获取语言名称
     * 
     * @param languageCode 语言代码
     * @return 语言名称
     */
    private String getLanguageName(String languageCode) {
        switch (languageCode) {
            case "zh": return "中文";
            case "en": return "英文";
            case "ja": return "日语";
            case "ko": return "韩语";
            case "fr": return "法语";
            case "de": return "德语";
            case "es": return "西班牙语";
            case "it": return "意大利语";
            case "ru": return "俄语";
            case "pt": return "葡萄牙语";
            case "ar": return "阿拉伯语";
            case "hi": return "印地语";
            case "th": return "泰语";
            case "vi": return "越南语";
            default: return languageCode;
        }
    }
    
    /**
     * 转义JSON字符串
     * 
     * @param input 输入字符串
     * @return 转义后的字符串
     */
    private String escapeJson(String input) {
        return input.replace("\\", "\\\\").replace("\"", "\\\"").replace("\n", "\\n");
    }
}